﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic.Security;
using System.Web.Security;

namespace Otgruzka.Account
{
    public partial class Login : System.Web.UI.Page
    {
        protected override void OnPreInit(EventArgs e)
        {
            if (!IsPostBack)
            {
                //Если пользователь уже авторизован, то всегда перенаправляем его на Главную
                if (User != null && User.Identity.IsAuthenticated)
                    Response.Redirect("~/", true);
            }
            base.OnPreInit(e);
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            //RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
            
            if (!IsPostBack)
            {
                this.txtLogin.Focus();
            }
        }


        protected void OnLoginClick(object sender, EventArgs e)
        {
            var authResult = AuthenticationService.AuthenticateUser(txtLogin.Text, txtPassword.Text);
            switch (authResult)
            {
                case 1:
                    string LGN = txtLogin.Text;
                    string PSS = (string.IsNullOrEmpty(txtPassword.Text)) ? "" : PasswordMD5Helper.GetMd5Hash(txtPassword.Text);

                    // Query the user store to get this user's User Data
                    string userDataString = string.Concat(PSS, "|", LGN);

                    // Create the cookie that contains the forms authentication ticket
                    HttpCookie authCookie = FormsAuthentication.GetAuthCookie(LGN, false);

                    // Get the FormsAuthenticationTicket out of the encrypted cookie
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

                    // Create a new FormsAuthenticationTicket that includes our custom User Data
                    FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userDataString);

                    // Update the authCookie's Value to use the encrypted version of newTicket
                    authCookie.Value = FormsAuthentication.Encrypt(newTicket);

                    FormsAuthentication.RenewTicketIfOld(newTicket); // Do before saving cookie

                    // Manually add the authCookie to the Cookies collection
                    Response.Cookies.Add(authCookie);


                    //FormsAuthentication.RedirectFromLoginPage(txtLogin.Text, chbStayInSystem.Checked);
                    string redirUrl = FormsAuthentication.GetRedirectUrl(txtLogin.Text, chbStayInSystem.Checked);
                    Response.Redirect(redirUrl);

                    break;
                case 0:
                    pnlErrorLoginMessage.Visible = true;
                    lblErrorMessage.Text = @"Вы указали неправильное имя пользователя или пароль.";
                    break;
                case 2:
                    pnlErrorLoginMessage.Visible = true;
                    lblErrorMessage.Text = @"Данная учетная запись заблокирована";
                    break;
            }
        }


    }
}
